<!-- file monitor -->
<script> 
	
	$(function(){
		/* REMOVE DUPLICATE ID */
		var ids = [];
		$('*').each(function() {
		    if (this.id && this.id !== '') {
		        if (ids[this.id]) {
		            $(this).remove();
		        } else {
		            ids[this.id] = this
		        }
		    }
		});
		
		/* external function */
		
        function format(state) {
			tambahan = "";
			if (typeof $(state.element[0]).attr("alt") != "undefined")
				tambahan = $(state.element[0]).attr("alt");
            return state.text+tambahan ; 
        }
		
		$.fn.getCombobox = function(data, key, label, desc){
			var field = $(this);
			field.html("<option></option>");
			$.ajax({
				url : "c_public_function",
				data : data,
				type : 'POST', dataType : 'json'
			}).done(function(response){
				for(i=0;i<response.length;i++){
					var option = "<option value='"+response[i][key]+"' ";
					if (typeof response[i][desc] != "undefined")
						option += " alt='<div class=desc>"+response[i][desc]+"</div>'";
						
					option += " >"+response[i][label]+"</option>";
					field.append(option);
				}
				
				field.select2({
					placeholder: "-",
					allowClear: true,
					formatResult: format,
					formatSelection: format,
					escapeMarkup: function (m) {
						return m;
					}
				});
			});
		}
		
		$.fn.serializeObject = function()
		{
		   var o = {};
		   var a = this.serializeArray();
		   $.each(a, function() {
			   if (o[this.name]) {
				   if (!o[this.name].push) {
					   o[this.name] = [o[this.name]];
				   }
				   o[this.name].push(this.value || '');
			   } else {
				   o[this.name] = this.value || '';
			   }
		   });
		   return o;
		};
		
		/* declarisasi */
		
		task_monitor = $("#task-monitor");
		grid_monitor = $("#grid-monitor");
		btnadd_monitor = $("#btn-add-monitor");
		btncancel_monitor =  $("#btn-cancel-monitor");
		btnsave_monitor = $("#btn-save-monitor");
		form_monitor = $("#form-monitor");
		portlet_monitor = $("#portlet-monitor");
		
		field_monitor_id = $("#monitor_id");
		field_m_proyek_id = $("#m_proyek_id");
		field_m_mandor_id = $("#m_mandor_id");
		field_monitor_periode = $("#monitor_periode");
		field_m_pembayaran_id = $("#m_pembayaran_id");
		field_m_pekerjaan_id = $("#m_pekerjaan_id");
		field_monitor_mulai = $("#monitor_mulai");
		field_monitor_selesai = $("#monitor_selesai");
		field_monitor_wakil = $("#monitor_wakil");
		field_monitor_tukang = $("#monitor_tukang");
		field_monitor_pekerja = $("#monitor_pekerja");
		field_monitor_koordinasi = $("#monitor_koordinasi");
		field_monitor_quality = $("#monitor_quality");
		field_monitor_safety = $("#monitor_safety");
		field_monitor_hk = $("#monitor_hk");
		field_monitor_grade = $("#monitor_grade");
		
		/* function */
		function pointToSkor(point){
            point = (parseInt(point)  || 0 );
            if (point < 50)
                skor = 1;
            else if (point < 70)
                skor = 2;
            else if (point < 85)
                skor = 3;
            else 
                skor = 4;
            
            return skor;
        }
        
        function calcGrade(){
            nilai1 = (parseInt(field_monitor_wakil.val())  || 0 )+
                    (parseInt(field_monitor_tukang.val()) || 0 ) +
                    (parseInt(field_monitor_pekerja.val()) || 0 );
            console.log(nilai1);
            
            if (nilai1 >= 100)
                nilai1 = 1;
            else if (nilai1 >= 50)
                nilai1 = 2;
            else 
                nilai1 = 3;
            
            nilai2 = pointToSkor(field_monitor_koordinasi.val() ) +
                    pointToSkor(field_monitor_quality.val() ) +
                    pointToSkor(field_monitor_safety.val() ) +
                    pointToSkor(field_monitor_hk.val() );
            
            console.log(nilai2);
            
            if (nilai2 >= 10)
                nilai2 = 1;
            else if (nilai2 >= 6)
                nilai2 = 2;
            else 
                nilai2 = 3;
            
            nilai = nilai1 + nilai2;
            
            if (nilai <= 3)
                grade = "Grade 1";
            else if (nilai <= 5)
                grade = "Grade 2";
            else 
                grade = "Grade 3";
            
            field_monitor_grade.val(grade);
        }
		/* method started */
		
		/* maybe you need * /
		
		field_task_assign_date.datepicker({ dateFormat : 'dd-MM-yy'});
		field_status.select2({
					placeholder: "-",
					allowClear: true,
					formatResult: format,
					formatSelection: format,
					escapeMarkup: function (m) {
						return m;
					}
				});
		m_staff_id.select2("val",dataRow.m_staff_id);
				
		/*                  */
		
		/* make component */
        
		field_m_proyek_id.getCombobox({task : "proyek"}, "proyek_id", "proyek_nama", "proyek_kode");
		field_m_mandor_id.getCombobox({task : "mandor"}, "mandor_id", "mandor_nama", "mandor_kode"); 
		field_m_pekerjaan_id.getCombobox({task : "pekerjaan"}, "pekerjaan_id", "pekerjaan_ket"); 
		field_m_pembayaran_id.getCombobox({task : "pembayaran"}, "pembayaran_id", "pembayaran_ket"); 
        field_monitor_periode.datepicker({ format : 'MM yyyy'});
        field_monitor_mulai.datepicker({ format : 'dd MM yyyy'});
        field_monitor_selesai.datepicker({ format : 'dd MM yyyy'});
        
		grid_monitor.unugrid({
			url: 'c_monitor',
			data: {task : 'LIST'},
			column :[
				{ label: 'Kode Proyek'  ,index: 'proyek_kode'  },
				{ label: 'Nama Proyek'  ,index: 'proyek_nama'  },
				{ label: 'Cabang'  ,index: 'cabang_nama'  },
				{ label: 'Vendor'  ,index: 'mandor_nama'  },
				{ label: 'Pembayaran'  ,index: 'pembayaran_ket'  },
				{ label: 'Pekerjaan'  ,index: 'pekerjaan_ket'  },
//				{ label: 'monitor_mulai'  ,index: 'monitor_mulai'  },
//				{ label: 'monitor_selesai'  ,index: 'monitor_selesai'  },
//				{ label: 'monitor_wakil'  ,index: 'monitor_wakil'  },
//				{ label: 'monitor_tukang'  ,index: 'monitor_tukang'  },
//				{ label: 'monitor_pekerja'  ,index: 'monitor_pekerja'  },
//				{ label: 'monitor_koordinasi'  ,index: 'monitor_koordinasi'  },
//				{ label: 'monitor_quality'  ,index: 'monitor_quality'  },
//				{ label: 'monitor_safety'  ,index: 'monitor_safety'  },
//				{ label: 'monitor_hk'  ,index: 'monitor_hk'  },
				
				{ label: ''  ,index: 'monitor_id',type: 'action' }
			],
			deleteClick : function(id,dataRow, c ){
				if (id != null){
					confr = confirm("Apa Anda yakin menghapus data ini?");
					if (confr){
						var data = $(this).data();
						$.ajax({
							type: 'POST',
							url: 'c_monitor',
							data: {monitor_id: id, task : 'DELETE'},
							success: function(response){
								if(response==1){
									grid_monitor.unugrid('refresh');
								}
							}
						});
					}
				}
			},
			editClick : function(id,dataRow, c ){
				if (id != null){
					task_monitor.val("UPDATE");
					
					field_monitor_id.val(dataRow.monitor_id);
					field_m_proyek_id.select2("val",dataRow.m_proyek_id);
                    console.log(dataRow.m_proyek_id);
					field_m_mandor_id.select2("val",dataRow.m_mandor_id);
					field_m_pembayaran_id.select2("val",dataRow.m_pembayaran_id);
					field_m_pekerjaan_id.select2("val",dataRow.m_pekerjaan_id);
					field_monitor_periode.val(dataRow.monitor_periode);
					field_monitor_mulai.val(dataRow.monitor_mulai);
					field_monitor_selesai.val(dataRow.monitor_selesai);
					field_monitor_wakil.val(dataRow.monitor_wakil);
					field_monitor_tukang.val(dataRow.monitor_tukang);
					field_monitor_pekerja.val(dataRow.monitor_pekerja);
					field_monitor_koordinasi.val(dataRow.monitor_koordinasi);
					field_monitor_quality.val(dataRow.monitor_quality);
					field_monitor_safety.val(dataRow.monitor_safety);
					field_monitor_hk.val(dataRow.monitor_hk);
					
                    $.ajax({
                        url : "c_monitor",
                        data : {task : "DETAIL", monitor_id : dataRow.monitor_id},
                        dataType : 'json',
                        type : 'post'
                    }).done(function(response){
                        $("#detail_harsat").html("");
                        for(i = 0; i < response.length; i++){
                                $("#detail_harsat").append('<div class="input-group harsat"><input name="harsat_ket" class="form-control input-small" placeholder=Keterangan value="'+response[i].harsat_ket+'" /><input name="harsat_satuan" class="form-control input-xsmall" placeholder=Satuan value="'+response[i].harsat_satuan+'" /><input name="harsat_nilai" class="currency form-control input-small" placeholder=Harga  value="'+response[i].harsat_nilai+'" /></div>');
                        }
                        
                        $(".currency").keyup(function(){
                            $(this).formatCurrency();
                        });
                        
                        $(".currency").keyup();
                    });
                    
                    calcGrade();
					portlet_monitor.show();
				}
			}
		});
        
		/* event */
		
        
		$(".search input").keypress(function(e){
            if (e.keyCode == 13){
                $(".search button").click();
            }
        });
        
		$(".search button").click(function(){
            inputsearch = $(".search input").val();
            grid_monitor.unugrid("setData",{ search : inputsearch});
            grid_monitor.unugrid("refresh");
        });
        
        $(".btnharsat").click(function(){
            data = $(this).data();
            if (data.operator == 1){
                $("#detail_harsat").append('<div class="input-group harsat"><input name="harsat_ket" class="form-control input-small" placeholder=Keterangan /><input name="harsat_satuan" class="form-control input-xsmall" placeholder=Satuan /><input name="harsat_nilai" class="currency form-control input-small" placeholder=Harga  /></div>');
            }else{
                $("#detail_harsat").find(".harsat:last").remove();
            }
            
		
            $(".currency").keyup(function(){
                $(this).formatCurrency();
            });
        });
        
        field_m_mandor_id.change(function(){
            value = field_m_mandor_id.val();
            field_m_pekerjaan_id.getCombobox({task : "pekerjaan", mandor_id : value}, "pekerjaan_id", "pekerjaan_ket"); 
        });
		btnadd_monitor.click(function(){
			btncancel_monitor.click();
			task_monitor.val("INSERT");
			portlet_monitor.show();
            
            $("#detail_harsat").html("");
            field_m_proyek_id.select2("val",0);
            field_m_mandor_id.select2("val",0);
            field_m_pembayaran_id.select2("val",0);
            field_m_pekerjaan_id.select2("val",0);
		});
		
		btncancel_monitor.click(function(){
			portlet_monitor.hide();
		});
		
		btnsave_monitor.click(function(){
            
            $(".currency").each(function(id,el){
                $(el).toNumber();
            });
            
			data = form_monitor.serializeObject();
			$.ajax({
				url : "c_monitor",
				data : data,
				type : 'POST'
			}).done(function(response){
				grid_monitor.unugrid('refresh');
				btncancel_monitor.click();
			});
		});
        
        $(".calc-grade").keyup(function(){
            calcGrade();
        });
        
        $(".mappingto").change(function(){
            data = $(this).data();
            $.ajax({
                url : "c_mapping",
                data : { task : "UPDATE", monitor_id : data.monitor_id, m_proyek_id : $(this).val()},
                type : "post",
            });
        });
        
        function setLabel(el){
                position = el.position();
                pos = position.left;
                width = el.width();
                start = parseInt(pos / 41);
                end = parseInt(((width) + pos) / 41);
                start = $("#list-mapping thead tr:nth-child(2) th").get(start).innerHTML;
                end = $("#list-mapping thead tr:nth-child(2) th").get(end).innerHTML;
            if (start != end)
                el.find("span").text( start+" - "+end );
            else
                el.find("span").text( start );
            
            return {start : start, end : end};
        }
        
        $(".mapdate").click(function(){
           if ($(this).hasClass("notactive")){
                $(this).removeClass("notactive");
                $(this).addClass("active");
                $(this).css("width","100%");
                setLabel($(this));
                $(this).resizable();
                $(this).draggable();
           }
        });
        
        $(".mapdate.active").resizable();
         $(".mapdate.active").draggable();
        $(".mapdate").resize(function(){
            el =$(this);
            width = el.width();
            nPos = el.position();
            if (nPos.left < 0){
                el.css("left","0px");
            }
            
            if ((width + nPos.left) > 490){
                el.css("left",(490 - width )+"px");
            }
            
            setLabel(el);
        });
        
        var isDrag; 
        var el;
        var pos;
        $(".mapdate").mousedown(function(){
            if ($(this).hasClass("ui-draggable")){
                isDrag = true;
                el = $(this);
                pos = el.position();
            }
        });
        
        $("*").mouseup(function(){
            if (isDrag){
                width = el.width();
                nPos = el.position();
                if (nPos.left < 0){
                    el.css("left","0px");
                }
                
                if ((width + nPos.left) > 490){
                    el.css("left",(490 - width )+"px");
                }
            
                result = setLabel(el);
                data = el.data();
                isDrag = false;
                el = null;
            }
        });
        $(".startdate, .enddate").datepicker({format : "dd MM yyyy", autoclose : true});
        
        $(".startdate, .enddate").on("changeDate",function(){
            data = $(this).data();
            endtext = $(this).parent().parent().find(".enddate");
            starttext = $(this).parent().parent().find(".startdate");
            end = $(endtext).val();
            start = $(starttext).val();
            timeend = new Date(end);
            timestart = new Date(start); 
            if (timeend < timestart){
                if($(this).hasClass("startdate")){
                    endtext.val(starttext.val());
                    end = start;
                }else{
                    starttext.val(endtext.val());
                    start = end;
                }
            }
             $.ajax({
                url : "c_mapping",
                data : { task : "UPDATE2", monitor_id : data.monitor_id, start : start, end : end},
                type : "post",
            });
        });
	});
</script>
<style>
    .harsat .currency{
        text-align:right;
    }
    thead tr th{
        text-align : center !important;
    }
    .mapdate{
        text-align:center;
        cursor : pointer;
        height:25px !important;
        top : 5px !important;
        position:absolute;
    }
    .mapdate.active{
        background:#5a4;
    }
    .mapdate.notactive{
        background:#999;
        width: 100% !important; 
    }
    .mapdate.notactive:hover{
        text-decoration : underline;
        font-weight : bold;
        color : #00f;
    }
    </style>
	 <div class="row">
		<div class="col-md-12">
		   <!-- BEGIN SAMPLE TABLE PORTLET-->
		   <div class="portlet box yellow">
			  <div class="portlet-title">
				 <div class="caption"><i class="icon-cogs"></i>Mapping</div>
				 <div class="tools">
					<a href="javascript:;" class="collapse"></a>
				 </div>
			  </div>
			  <div class="portlet-body flip-scroll">
			<p>&nbsp;</p>
			
                      <div class="input-group search">
                         <input type="text" class="form-control" placeholder="Filter">
                         <span class="input-group-btn">
                         <button type="button" class="btn yellow">Search !</button>
                         </span>
                      </div>
			<p>&nbsp;</p>
            <div id="list-mapping" class="table-responsive" style="overflow-x:scroll">
                <table class="table  table-striped table-bordered table-advance flip-content table-hover">
                <thead>
                    <tr>
                    <th rowspan=2  style="min-width:100px">Proyek</th>
                    <th rowspan=2  style="min-width:100px">Mandor</th>
                    <th rowspan=2  style="min-width:100px">Renc Selesai</th>
                    <th rowspan=2  style="min-width:100px">Pekerjaan</th>
                    <th rowspan=2  style="min-width:200px">Ke Proyek</th>
                    <th colspan=2  style="min-width:200px">Periode</th >
                    </tr>  
                    <tr>
                        <th>Mulai</th>
                        <th>Selesai</th>
                        </tr>
                    <!-- tr>
                        <?php $m = date("m"); 
                            for($i=0;$i<12;$i++){
                                
                                echo "<th>".date("M",strtotime("01-".$m."-".date("Y")))."</th>";
                                $m++;
                                $m %= 12;
                            }

                        
                        ?>
                    </tr -->
                </thead>
                    <tbody>
                    
                    <?php foreach($list as $row){
                        $html_proyek = "";
                        foreach($proyek as $option){
                            if ($option->proyek_id == $row->to_proyek_id){
                            $html_proyek .= "<option value=".$option->proyek_id." selected>".$option->proyek_nama."</option>";
                            }else{
                            $html_proyek .= "<option value=".$option->proyek_id.">".$option->proyek_nama."</option>";
                            }
                        }
                            
                        ?>
                        <tr>
                        <td><?php echo $row->proyek_nama ;?></td>
                        <td><?php echo $row->mandor_nama ;?></td>
                        <td><?php echo date("d M Y",strtotime($row->monitor_selesai)) ;?></td>
                        <td><?php echo $row->pekerjaan_ket ;?></td>
                        <td><select class="mappingto" data-monitor_id="<?php echo $row->monitor_id ;?>">
                            <option>-</option>
                            <?php echo $html_proyek; ?>
                            </select></td>
                        <td>
                            <input class="startdate"  data-monitor_id="<?php echo $row->monitor_id ;?>" value="<?php $time = strtotime( $row->mapping_tglmulai);
                                if ($time > 0)
                                    echo date("d F Y",$time);
                                                                                                               ?>" />
                            </td>
                        <td>
                            <input class="enddate"  data-monitor_id="<?php echo $row->monitor_id ;?>" value="<?php $time = strtotime( $row->mapping_tglselesai);
                                if ($time > 0)
                                    echo date("d F Y",$time); ?>" />
                            </td>
                            <?php /* if($row->mapping_tglmulai != ""){ 
                                $mapping_tglmulai = $row->mapping_tglmulai ;
                                $mapping_tglselesai = $row->mapping_tglselesai ;
                                if (strtotime($mapping_tglmulai) < time())
                                    $startMonth = date("m");
                                else
                                    $startMonth = date("m",strtotime($mapping_tglmulai));
                            
                                if (strtotime($mapping_tglselesai) > strtotime("+1 year"))
                                        $endMonth = date("m",strtotime("+1 year"));
                                    else
                                        $endMonth = date("m",strtotime($mapping_tglselesai));
                                
                                if ($endMonth >= $startMonth)
                                    $diff = $endMonth - $startMonth;
                                else
                                    $diff = ($endMonth + 12) - $startMonth;
                            
                                if ($startMonth >= date("m"))
                                    $left = ($startMonth - date("m")) * 41;
                                else
                                    $left = (($startMonth + 12) - date("m")) * 41;
                            
                                $width = ($diff + 1)* 40;
                                $startMonth = date("M",strtotime("01-".$startMonth."-2000"));
                                $endMonth = date("M",strtotime("01-".$endMonth."-2000"));
                            if ( $startMonth != $endMonth)
                                $label = $startMonth." - ".$endMonth;
                            else
                                $label = $startMonth; 
                        </tr>*/ 
                      }  ?>
                    </tbody>
                </table>  
            </div>
				</div>
			 </div>
		</div>
	</div>